package com.quanta.edaily.controller;


import com.quanta.edaily.Service.HahaService;
import com.quanta.edaily.bean.JsonResponse;
import com.quanta.edaily.bean.contants.ResultCode;
import com.quanta.edaily.pojo.Haha;
import jakarta.annotation.Nullable;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.Min;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/haha")
@Validated
public class HahaController {
    @Resource
    HahaService hahaService;

    @PostMapping("/insert")
    public JsonResponse insert(@RequestBody Haha haha) {
        if (hahaService.insert(haha) == 1) return JsonResponse.success("插入成功");
        else return JsonResponse.error(ResultCode.SERVICE_ERROR, "插入失败");
    }

    @PostMapping("/deleteById/{id}")
    public JsonResponse deleteById(@PathVariable Integer id) {
        if (hahaService.deleteById(id) == 1) return JsonResponse.success("删除成功");
        else return JsonResponse.error(ResultCode.SERVICE_ERROR, "删除失败");
    }

    @PostMapping("/updateById")
    public JsonResponse updateById(@RequestBody Haha haha) {
        if (hahaService.updateById(haha) == 1) return JsonResponse.success("更改成功");
        else return JsonResponse.error(ResultCode.SERVICE_ERROR, "更改失败");
    }

    @GetMapping("/getById/{id}")
    public JsonResponse getById(@PathVariable Integer id) {
        Haha haha = hahaService.getById(id);
        if (haha == null)
            return JsonResponse.paramError("查询失败");
        haha.setReadCount(haha.getReadCount() == null ? 0 : haha.getReadCount() + 1);
        hahaService.updateById(haha);
        return JsonResponse.success("查询成功", haha);
    }

    @GetMapping("/getSome")
    public JsonResponse findPage(@Nullable @RequestParam @Min(1) Integer pageNum,
                                 @Nullable @RequestParam @Min(1) Integer pageSize,
                                 @Nullable @RequestParam String title) {
        if (pageNum == null && pageSize == null)
            return JsonResponse.success("查询成功", hahaService.getSome(null, null, title));
        if (pageNum != null && pageSize != null)
            return JsonResponse.success("查询成功", hahaService.getSome((pageNum - 1) * pageSize, pageSize, title));
        return JsonResponse.paramError("参数错误");
    }
}
